<template>
  <div class="prescription-management">
    <div class="header">
      <h2>药方管理</h2>
      <el-button v-if="!isAdmin" type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        开具药方
      </el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="患者姓名">
          <el-input
            v-model="searchForm.patientName"
            placeholder="请输入患者姓名"
            clearable
            @clear="handleSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="处方编号">
          <el-input
            v-model="searchForm.prescriptionNo"
            placeholder="请输入处方编号"
            clearable
            @clear="handleSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="处方状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待审核" :value="0" />
            <el-option label="已审核" :value="1" />
            <el-option label="已配药" :value="2" />
            <el-option label="已完成" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="处方类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="西药" :value="1" />
            <el-option label="中药" :value="2" />
            <el-option label="检查" :value="3" />
            <el-option label="治疗" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="开具日期">
          <el-date-picker
            v-model="searchForm.prescribeDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.total }}</div>
            <div class="stat-label">总处方数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.pending }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.dispensed }}</div>
            <div class="stat-label">已配药</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 药方列表 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      stripe
      style="width: 100%"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="prescriptionNo" label="处方编号" width="140" />
      <el-table-column prop="userName" label="患者姓名" width="100" />
      <el-table-column prop="doctorName" label="开具医生" width="100" />
      <el-table-column prop="departmentName" label="科室" width="120" />
      <el-table-column prop="type" label="处方类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTypeTagType(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额" width="100">
        <template #default="{ row }">
          ¥{{ row.totalAmount }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="prescribeTime" label="开具时间" width="160" sortable="custom">
        <template #default="{ row }">
          {{ formatDateTime(row.prescribeTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="reviewTime" label="审核时间" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.reviewTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="dispenseTime" label="配药时间" width="160">
        <template #default="{ row }">
          {{ formatDateTime(row.dispenseTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            <el-icon><View /></el-icon>
            详情
          </el-button>
          <el-button
            v-if="row.status === 0"
            type="warning"
            size="small"
            @click="handleReview(row)"
          >
            审核
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="success"
            size="small"
            @click="handleDispense(row)"
          >
            配药
          </el-button>
          <el-button
            v-if="row.status === 2"
            type="info"
            size="small"
            @click="handleComplete(row)"
          >
            完成
          </el-button>
          <el-button
            v-if="row.status === 0"
            type="danger"
            size="small"
            @click="handleCancel(row)"
          >
            取消
          </el-button>
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, View } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import request from '@/api/request'
import { addDialog } from '@/components/gDialog/index'
import prescriptionHandle from '@/views/adminModal/prescriptionHandle.vue'
import prescriptionDetailHandle from '@/views/adminModal/prescriptionDetailHandle.vue'

// 响应式数据
const userStore = useUserStore()
const isAdmin = computed(() => userStore.isAdmin)
const loading = ref(false)
const submitting = ref(false)
const tableData = ref([])
const selectedPrescription = ref(null)
const patientList = ref([])

// 搜索表单
const searchForm = reactive({
  patientName: '',
  prescriptionNo: '',
  status: '',
  type: '',
  prescribeDate: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 排序数据
const sortData = reactive({
  prop: '',
  order: ''
})

// 统计数据
const statistics = computed(() => {
  const total = tableData.value.length
  const pending = tableData.value.filter(item => item.status === 0).length
  const dispensed = tableData.value.filter(item => item.status === 2).length
  const completed = tableData.value.filter(item => item.status === 3).length
  
  return { total, pending, dispensed, completed }
})

// 页面加载时获取数据
onMounted(() => {
  fetchPrescriptions()
  fetchPatients()
})

// 获取处方列表
const fetchPrescriptions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await request.get('/business/prescriptions', { params })
    
    if (response.code === 200) {
      // 如果返回的是数组，直接使用；如果是分页对象，取其中的数据
      if (Array.isArray(response.data)) {
        tableData.value = response.data
        pagination.total = response.data.length
      } else {
        tableData.value = response.data.list || []
        pagination.total = response.data.total || 0
      }
    } else {
      ElMessage.error(response.message || '获取处方列表失败')
    }
  } catch (error) {
    console.error('获取处方列表失败:', error)
    ElMessage.error('获取处方列表失败')
  } finally {
    loading.value = false
  }
}

// 获取患者列表
const fetchPatients = async () => {
  try {
    const response = await request.get('/admin/users', {
      params: { role: 1 } // 只获取患者
    })
    if (response.code === 200) {
      if (Array.isArray(response.data)) {
        patientList.value = response.data
      } else {
        patientList.value = response.data.list || []
      }
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchPrescriptions()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    patientName: '',
    prescriptionNo: '',
    status: '',
    type: '',
    prescribeDate: ''
  })
  pagination.page = 1
  fetchPrescriptions()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchPrescriptions()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchPrescriptions()
}

// 排序改变
const handleSortChange = ({ prop, order }) => {
  sortData.prop = prop
  sortData.order = order
  fetchPrescriptions()
}

// 添加处方
const handleAdd = () => {
  addDialog({
    title: '开具处方',
    component: prescriptionHandle,
    width: '800px',
    props: {
      prescriptionData: {},
      isEdit: false,
      patientList: patientList.value
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchPrescriptions()
      }
    }
  })
}

// 编辑处方
const handleEdit = (row) => {
  addDialog({
    title: '编辑处方',
    component: prescriptionHandle,
    width: '800px',
    props: {
      prescriptionData: row,
      isEdit: true,
      patientList: patientList.value
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchPrescriptions()
      }
    }
  })
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const response = await request.get(`/business/prescription/${row.id}`)
    if (response.code === 200) {
      addDialog({
        title: '处方详情',
        component: prescriptionDetailHandle,
        width: '700px',
        props: {
          prescriptionData: response.data
        }
      })
    } else {
      ElMessage.error(response.message || '获取处方详情失败')
    }
  } catch (error) {
    console.error('获取处方详情失败:', error)
    ElMessage.error('获取处方详情失败')
  }
}

// 审核处方
const handleReview = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要审核处方"${row.prescriptionNo}"吗？`,
      '确认审核',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await request.put('/business/prescription/review', {
      prescriptionId: row.id
    })

    if (response.code === 200) {
      ElMessage.success('审核成功')
      fetchPrescriptions()
    } else {
      ElMessage.error(response.message || '审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核处方失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

// 配药
const handleDispense = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要为处方"${row.prescriptionNo}"配药吗？`,
      '确认配药',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await request.put('/business/prescription/dispense', {
      prescriptionId: row.id
    })

    if (response.code === 200) {
      ElMessage.success('配药成功')
      fetchPrescriptions()
    } else {
      ElMessage.error(response.message || '配药失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('配药失败:', error)
      ElMessage.error('配药失败')
    }
  }
}

// 完成处方
const handleComplete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要完成处方"${row.prescriptionNo}"吗？`,
      '确认完成',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await request.put('/business/prescription', {
      ...row,
      status: 3
    })

    if (response.code === 200) {
      ElMessage.success('处方已完成')
      fetchPrescriptions()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成处方失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 取消处方
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消处方"${row.prescriptionNo}"吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await request.put('/business/prescription', {
      ...row,
      status: 4
    })

    if (response.code === 200) {
      ElMessage.success('处方已取消')
      fetchPrescriptions()
    } else {
      ElMessage.error(response.message || '取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消处方失败:', error)
      ElMessage.error('取消失败')
    }
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '已审核',
    2: '已配药',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: '西药',
    2: '中药',
    3: '检查',
    4: '治疗'
  }
  return typeMap[type] || '未知'
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info'
  }
  return typeMap[type] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}
</script>

<style scoped>
.prescription-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 4px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-content {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  padding: 20px 20px 10px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style> 